﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.IO;
using System.Net;
using System.Threading.Tasks;
using System.Windows.Media.Imaging;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;

namespace MiniChat
{
   public static class Client
    {
        public static void ProcessMessage(string message, Socket sock,ref bool Logged)
        {
            message = Ullity.Trim(message);
            Ullity.Log(message);
            var arr_msg = message.Split(':');
            switch (arr_msg[0])
            {
                case ("loginstatus"):
                    if (arr_msg.Length == 2) {
                        if (arr_msg[1] == "True")
                        {
                            Logged = true;
                        }
                        else {
                            Logged = false;
                        }
                    }
                    break;
                case("PING"):
                    if (arr_msg.Length == 2) { Send("REPING:" + arr_msg[1], sock); }
                    break;
                case("info"):
                    if (arr_msg.Length == 2) {
                        var sdata =Ullity.Split(arr_msg[1],",");
                        foreach (string s in sdata)
                        {
                            if (s.Contains("http_avatar=")) {
                                CGlobalVariable.HttpImageServer = "http://" + s.Replace("http_avatar=","");
                            }
                            else if (s.Contains("http_avatar="))
                            {
                                CGlobalVariable.HttpImageServer = "http://" + s.Replace("http_server=", "");
                            }else if(s.Contains("fullname=")){
                                CGlobalVariable.FullName = s.Replace("fullname=", "");
                                /*
                                CGlobalVariable.txtName.Dispatcher.Invoke(new Action(
                                    ()=>{
                                        CGlobalVariable.txtName.Text = CGlobalVariable.FullName;
                                        }
                                    ));*/
                            }
                            else if (s.Contains("statustext="))
                            {
                                /*
                                CGlobalVariable.txtStatustext.Dispatcher.Invoke(
                                        new Action(() => {
                                            CGlobalVariable.txtStatustext.Text = s.Replace("statustext=", ""); ;
                                        })
                                    );*/
                            }
                            else if (s.Contains("useravatar="))
                            {/*
                                CGlobalVariable.UserAvatar = s.Replace("useravatar=", "");
                                DownloadTask dl = new DownloadTask()
                                {
                                    url = CGlobalVariable.HttpImageServer + CGlobalVariable.UserAvatar + ".jpg",
                                    username = CGlobalVariable.UserName
                                };
                                dl.action = new System.Threading.Tasks.Task(
                                    new Action(() =>
                                    {
                                        CGlobalVariable.imgUserAvatar.Dispatcher.Invoke(
                                                new Action(() =>
                                                {
                                                    try
                                                    {
                                                        BitmapImage bmi = new BitmapImage(new Uri(Path.Combine(CGlobalVariable.ImagePath, CGlobalVariable.UserName + ".jpg"), UriKind.Absolute));
                                                        CGlobalVariable.imgUserAvatar.Source = bmi;
                                                    }
                                                    catch {
                                                        Ullity.Log("Can't load avatar " + Path.Combine(CGlobalVariable.ImagePath, CGlobalVariable.UserName + ".jpg"), 3);
                                                    }
                                                })
                                            );
                                    })
                                    );
                                listdownload.Enqueue(dl);
                                download();*/
                            }
                        }
                    }
                    break;
                case("adduserstatus"):
                    if (arr_msg.Length == 2) {
                        if (arr_msg[1] == "True")
                        {
                            MessageBox.Show("Thêm bạn mới thành công !");
                        }
                        else {
                            MessageBox.Show("Thêm bạn mới thất bại !");
                        }
                    }
                    break;
                case ("updateuser"):
                    if (arr_msg.Length == 2)
                    {
                        var arrcontact = arr_msg[1].Split('|');
                        ContactItem ci = new ContactItem()
                        {
                            ContactName = arrcontact[0],
                            ContactFullName = arrcontact[1],
                            ContactImage = arrcontact[2],
                            ContastStatus = int.Parse(arrcontact[3])
                        };
                        CGlobalVariable.lsbContacts.Dispatcher.BeginInvoke(new Action(
                                     () => {
                                         
                                         for (int i = 0; i < CGlobalVariable.lsbContacts.Items.Count; i++) {
                                             ContactItem ct = (ContactItem)((StackPanel)CGlobalVariable.lsbContacts.Items[i]).Tag;
                                             if (ct.ContactName == ci.ContactName) {
                                                 SolidColorBrush sbr = new SolidColorBrush(Color.FromArgb(100, 100, 100, 100));
                                                 if (ci.ContastStatus == 1)
                                                 {
                                                     sbr = new SolidColorBrush(Color.FromArgb(80, 142, 255, 1));
                                                 }
                                                 ((StackPanel)CGlobalVariable.lsbContacts.Items[i]).Background = sbr;
                                                 
                                             }
                                         }
                                         
                                         }
                                     
                                     ));
                    }
                    break;
                case ("friendlist"):
                    if (arr_msg.Length == 2)
                    {
                        string listuser = arr_msg[1];
                        if (listuser == null) { return; }                      
                        var arrls = Ullity.Split(listuser,",");
                        foreach (string u in arrls)
                        {
                            if (u != "") {
                                //for(int ia =0 ;ia <100;ia++){
                                var arrcontact = u.Split('|');
                                ContactItem ci = new ContactItem() { 
                                    ContactName = arrcontact[0],
                                    ContactFullName = arrcontact[1],
                                    ContactImage = arrcontact[2],
                                    ContastStatus = int.Parse(arrcontact[3])
                                };
                                int itemindex = 0;
                                CGlobalVariable.lsbContacts.Dispatcher.BeginInvoke(new Action(
                                    () => {
                                        SolidColorBrush sbr = new SolidColorBrush(Color.FromArgb(100, 100, 100, 100));
                                        if (ci.ContastStatus == 1) {
                                            sbr = new SolidColorBrush(Color.FromArgb(80, 142, 255, 1));
                                        }
                                        
                                        StackPanel lbst = new StackPanel()
                                        {
                                            Height=128,
                                            Width=128,
                                            Background = sbr,
                                            Margin = new Thickness(2),
                                            Tag = ci,
                                        };
                                        BitmapImage bm = new BitmapImage(new Uri("/Images/no_avatar.png",UriKind.Relative));
                                        Image i = new Image()
                                        {
                                            Height = 80,
                                            Width=80,
                                            VerticalAlignment  = System.Windows.VerticalAlignment.Center,
                                            Source = bm
                                        };
                                        TextBlock tbfname = new TextBlock() { 
                                            Text = ci.ContactFullName,
                                            FontSize = 22,
                                            TextAlignment = TextAlignment.Center
                                        };
                                        TextBlock tbname = new TextBlock()
                                        {
                                            Text = ci.ContactName,
                                            FontSize = 14,
                                            TextAlignment = TextAlignment.Center
                                        };
                                        lbst.Children.Add(i);
                                        lbst.Children.Add(tbfname);
                                        lbst.Children.Add(tbname);
                                        CGlobalVariable.lsbContacts.Items.Add(lbst);
                                    }
                                    ));
                                /*
                                DownloadTask dl = new DownloadTask()
                                {
                                    url = CGlobalVariable.HttpImageServer + ci.ContactImage + ".jpg",
                                    username = ci.ContactName                                  
                                };
                                dl.action = new Task(
                                        new Action(()=>{
                                            CGlobalVariable.lsbContacts.Dispatcher.Invoke(new Action(
                                                () =>
                                                {
                                                    StackPanel ls = (StackPanel)CGlobalVariable.lsbContacts.Items[itemindex];
                                                    Image i = (Image)ls.Children[0];
                                                    if(File.Exists(Path.Combine(CGlobalVariable.ImagePath, ci.ContactName + ".jpg"))){
                                                        BitmapImage bm = new BitmapImage(new Uri(Path.Combine(CGlobalVariable.ImagePath, ci.ContactName + ".jpg"), UriKind.Absolute));
                                                        i.Source = bm;
                                                    }

                                                })
                                                );
                                          })
                                    );
                                listdownload.Enqueue(dl);
                                download();
                            //}*/
                            }
                        
                        }
                       
                    }
                    break;
                case("removefriend"):
                    
                        
                            CGlobalVariable.lsbContacts.Dispatcher.BeginInvoke(
                                new Action(() => {
                                    for (int i = 0; i < CGlobalVariable.lsbContacts.Items.Count; i++)
                                     {
                       
                                    ContactItem ct = (ContactItem)((StackPanel)CGlobalVariable.lsbContacts.Items[i]).Tag;
                                        if (ct.ContactName == arr_msg[1])
                                        {
                                            CGlobalVariable.lsbContacts.Items.RemoveAt(i);
                                            i = CGlobalVariable.lsbContacts.Items.Count;
                                        }  
                                     }
                                })
                                );
                        
                    
                    break;
                case ("showmsg"):
                    MessageBox.Show(arr_msg[1]);
                    CGlobalVariable.IsDisconnected = true;                   
                    return;
                case ("addfriend"):
                    if (arr_msg[1] != "")
                    {
                        //for(int ia =0 ;ia <100;ia++){
                        var arrcontact = arr_msg[1].Split('|');
                        ContactItem ci = new ContactItem()
                        {
                            ContactName = arrcontact[0],
                            ContactFullName = arrcontact[1],
                            ContactImage = arrcontact[2],
                            ContastStatus = int.Parse(arrcontact[3])
                        };
                        CGlobalVariable.lsbContacts.Dispatcher.BeginInvoke(new Action(
                            () =>
                            {
                                SolidColorBrush sbr = new SolidColorBrush(Color.FromArgb(100, 100, 100, 100));
                                if (ci.ContastStatus == 1)
                                {
                                    sbr = new SolidColorBrush(Color.FromArgb(80, 142, 255, 1));
                                }

                                StackPanel lbst = new StackPanel()
                                {
                                    Height = 128,
                                    Width = 128,
                                    Background = sbr,
                                    Margin = new Thickness(2),
                                    Tag = ci,
                                };
                                BitmapImage bm = new BitmapImage(new Uri("/Images/no_avatar.png", UriKind.Relative));
                                Image i = new Image()
                                {
                                    Height = 80,
                                    Width = 80,
                                    VerticalAlignment = System.Windows.VerticalAlignment.Center,
                                    Source = bm
                                };
                                TextBlock tbfname = new TextBlock()
                                {
                                    Text = ci.ContactFullName,
                                    FontSize = 22,
                                    TextAlignment = TextAlignment.Center
                                };
                                TextBlock tbname = new TextBlock()
                                {
                                    Text = ci.ContactName,
                                    FontSize = 14,
                                    TextAlignment = TextAlignment.Center
                                };
                                lbst.Children.Add(i);
                                lbst.Children.Add(tbfname);
                                lbst.Children.Add(tbname);
                                CGlobalVariable.lsbContacts.Items.Add(lbst);
                            }
                            ));
                    }
                    break;
                //"offlinemsg:1|addfriendnotice&#01$ B?n Huy(ngxhuy1) mu?n thêm b?n vào danh sách b?n bè&#02$ b?n có đ?ng ? không ?&#01$ngxhuy1|146393906,"
                case ("showchat"):
                    if (arr_msg.Length > 2) { 
                        
                    }
                    break;
                case("addfriendnotice"):
                    string strnt = Ullity.DecodeString(arr_msg[1]);
                    CGlobalVariable.lsbCurentChats.Dispatcher.BeginInvoke(new Action(() =>
                    {
                        List<object> a = new List<object>();
                        if (!CGlobalVariable.lstChatData.ContainsKey("system"))
                        {
                            StackPanel lbst = new StackPanel()
                            {
                                Height = 48,
                                Width = 48,
                                Background = new SolidColorBrush(Colors.Blue),
                                Margin = new Thickness(2),
                                Tag = "system"
                            };

                            Image i = new Image()
                            {
                                Height = 24,
                                Width = 24,
                                VerticalAlignment = System.Windows.VerticalAlignment.Center,
                                Source = new BitmapImage(new Uri("/Images/Share alt 2.png", UriKind.Relative))
                            };
                            TextBlock tbfname = new TextBlock()
                            {
                                Text = "system",
                                FontSize = 8,
                                TextAlignment = TextAlignment.Center
                            };
                            lbst.Children.Add(i);
                            lbst.Children.Add(tbfname);
                            CGlobalVariable.lsbCurentChats.Items.Add(lbst);
                            CGlobalVariable.lsbCurentChats.SelectedItem = lbst;
                        }
                        else
                        {
                            a = CGlobalVariable.lstChatData["system"].chatData;
                        }
                        a.Add(new TextBlock()
                        {
                            Text = Ullity.DecodeString(strnt),
                            FontSize = 14,
                            TextAlignment = System.Windows.TextAlignment.Right,
                            HorizontalAlignment = System.Windows.HorizontalAlignment.Stretch,
                            Width = CGlobalVariable.lsbChatWindows.Width,
                            Padding = new Thickness(50, 2, 2, 2),
                            //Background = new SolidColorBrush(Color.FromArgb(30, 240, 10, 150)),
                            TextWrapping = TextWrapping.Wrap
                        });
                        Button b = new Button()
                        {
                            Content = "Click vào đây để thêm bạn.",
                            Tag = arr_msg[2]
                        };
                        b.Click += new RoutedEventHandler(b_Click);
                        a.Add(b);
                        if(!CGlobalVariable.lstChatData.ContainsKey("system")){
                            CGlobalVariable.lstChatData.Add("system", new Msgs()
                            {
                                contactboxid = -1,
                                curentchatboxid = 0,
                                chatData = a
                            });
                        }else{
                            CGlobalVariable.lstChatData["system"].chatData= a;
                        }
                     
                        showChat("system");
                    }));

                    break;
                case ("offlinemsg"):
                    if (arr_msg.Length == 2)
                    {
                        var msg = Ullity.Split(arr_msg[1], "|");
                        if (msg.Length > 2)
                        {
                            var arr_offmsg = Ullity.Split(arr_msg[1], ",");
                            foreach(string m  in arr_offmsg)
                            {
                                    var str_a = m.Split('|');
                                    string uname = str_a[0];
                                    string str = str_a[1];
                                    string time = str_a[2];                                 
                                    string fullname = str_a[3];
                                    var s = Ullity.Split(Ullity.DecodeString(str), ":");
                                    if (s.Length > 0) {
                                        switch (s[0])
                                        {
                                            case ("addfriendnotice"):
                                                CGlobalVariable.lsbCurentChats.Dispatcher.BeginInvoke(new Action(() =>
                                                {
                                                    StackPanel lbst = new StackPanel()
                                                    {
                                                        Height = 48,
                                                        Width = 48,
                                                        Background = new SolidColorBrush(Colors.Blue),
                                                        Margin = new Thickness(2),
                                                        Tag = "system"
                                                    };
                                              
                                                    Image i = new Image()
                                                    {
                                                        Height = 24,
                                                        Width = 24,
                                                        VerticalAlignment = System.Windows.VerticalAlignment.Center,
                                                        Source = new BitmapImage(new Uri("/Images/Share alt 2.png", UriKind.Relative))
                                                    };
                                                    TextBlock tbfname = new TextBlock()
                                                    {
                                                        Text = "system",
                                                        FontSize = 8,
                                                        TextAlignment = TextAlignment.Center
                                                    };
                                                    lbst.Children.Add(i);
                                                    lbst.Children.Add(tbfname);
                                                    CGlobalVariable.lsbCurentChats.Items.Add(lbst);
                                                    CGlobalVariable.lsbCurentChats.SelectedItem = lbst;
                                                    List<object> a = new List<object>();
                                                    a.Add(new TextBlock()
                                                    {
                                                        Text = Ullity.DecodeString(s[1]),
                                                        FontSize = 14,
                                                        TextAlignment = System.Windows.TextAlignment.Right,
                                                        HorizontalAlignment = System.Windows.HorizontalAlignment.Stretch,
                                                        Width = CGlobalVariable.lsbChatWindows.Width,
                                                        Padding = new Thickness(50,2,2,2),
                                                       // Background = new SolidColorBrush(Color.FromArgb(30, 240, 10, 150)),
                                                        TextWrapping = TextWrapping.Wrap
                                                    });
                                                    Button b = new Button()
                                                    {
                                                        Content = "Click vào đây để thêm bạn.",
                                                        Tag = s[2]
                                                    };
                                                    b.Click += new RoutedEventHandler(b_Click);
                                                    a.Add(b);
                                                    CGlobalVariable.lstChatData.Add("system", new Msgs()
                                                    {
                                                        contactboxid = -1,
                                                        curentchatboxid = 0,
                                                        chatData = a
                                                    });
                                                    showChat("system");
                                                }));

                                                break;
                                            case("sendmsg"):
                                                  uname = Ullity.DecodeString(s[2]);
                                                  fullname = "";
                                                  if (s.Length > 3) { fullname = Ullity.DecodeString(s[3]); }
                                                  str = Ullity.DecodeString(s[1]);   
                                                CGlobalVariable.lsbCurentChats.Dispatcher.BeginInvoke(new Action(() =>
                                                {                                                    
                                                  
                                                    List<object> a = new List<object>();
                                                    if (CGlobalVariable.lstChatData.ContainsKey(uname))
                                                    {
                                                        a = CGlobalVariable.lstChatData[uname].chatData;
                                                    }
                                                    else
                                                    {
                                                        StackPanel lbst = new StackPanel()
                                                        {
                                                            Height = 48,
                                                            Width = 48,
                                                            Background = new SolidColorBrush(Colors.Blue),
                                                            Margin = new Thickness(2),
                                                            HorizontalAlignment = System.Windows.HorizontalAlignment.Stretch,
                                                            Tag = uname
                                                        };
                                                        Uri imgs = new Uri(@"/Images/no_avatar.png", UriKind.Relative);
                                                       // if (File.Exists(Path.Combine(CGlobalVariable.ImagePath, uname + ".jpg")))
                                                       // {
                                                       //     imgs = new Uri(Path.Combine(CGlobalVariable.ImagePath, uname + ".jpg"), UriKind.Absolute);
                                                       /// }
                                                        Image i = new Image()
                                                        {
                                                            Height = 24,
                                                            Width = 24,
                                                            VerticalAlignment = System.Windows.VerticalAlignment.Center,
                                                            Source = new BitmapImage(imgs)
                                                        };
                                                        TextBlock tbfname = new TextBlock()
                                                        {
                                                            Text = (Ullity.Trim(fullname) != "") ? fullname : uname,
                                                            FontSize = 8,
                                                            TextAlignment = TextAlignment.Center
                                                        };
                                                        lbst.Children.Add(i);
                                                        lbst.Children.Add(tbfname);
                                                        CGlobalVariable.lsbCurentChats.Items.Add(lbst);
                                                        CGlobalVariable.lsbCurentChats.SelectedItem = lbst;
                                                    
                                                    }
                                                    a.Add(new TextBlock()
                                                    {
                                                        Text = Ullity.DecodeString(str),
                                                        FontSize = 14,
                                                        Padding = new Thickness(50, 2, 2, 2),
                                                        Width = CGlobalVariable.lsbChatWindows.Width,
                                                        TextAlignment = System.Windows.TextAlignment.Right,
                                                        HorizontalAlignment = System.Windows.HorizontalAlignment.Stretch,
                                                       // Background = new SolidColorBrush(Color.FromArgb(30, 240, 10, 150)),
                                                        TextWrapping = TextWrapping.Wrap
                                                    });
                                                    if (CGlobalVariable.lstChatData.ContainsKey(uname))
                                                    {
                                                        CGlobalVariable.lstChatData[uname].chatData = a;
                                                    }
                                                    else { 
                                                        CGlobalVariable.lstChatData.Add(uname, new Msgs()
                                                        {
                                                            contactboxid = -1,
                                                            curentchatboxid = 0,
                                                            chatData = a
                                                        });
                                                    }
                                                    
                                                    showChat(uname);
                                                }));

                                                Ullity.Log(uname + " -> " + str); 
                                                break;
                                        
                                        }
                                }
                             
                            Ullity.Log(m);
                            }
                        }
                    }
                    break;
                case ("sendmsg"):
                                    string uname1 = Ullity.DecodeString(arr_msg[2]);
                                    string fullname1 = Ullity.DecodeString(arr_msg[3]);  
                                    string str1 = Ullity.DecodeString(arr_msg[1]);                    
                                    CGlobalVariable.lsbCurentChats.Dispatcher.BeginInvoke(new Action(() =>
                                                {                                                    
                                                  
                                                    List<object> a = new List<object>();
                                                    if (CGlobalVariable.lstChatData.ContainsKey(uname1))
                                                    {
                                                        a = CGlobalVariable.lstChatData[uname1].chatData;
                                                    }
                                                    else
                                                    {
                                                        StackPanel lbst = new StackPanel()
                                                        {
                                                            Height = 48,
                                                            Width = 48,
                                                            Background = new SolidColorBrush(Colors.Blue),
                                                            Margin = new Thickness(2),
                                                            HorizontalAlignment = System.Windows.HorizontalAlignment.Stretch,
                                                            Tag = uname1
                                                        };
                                                        Uri imgs = new Uri(@"/Images/no_avatar.png", UriKind.Relative);
                                                        //if (File.Exists(Path.Combine(CGlobalVariable.ImagePath, uname1 + ".jpg")))
                                                        //{
                                                        //    imgs = new Uri(Path.Combine(CGlobalVariable.ImagePath, uname1 + ".jpg"), UriKind.Absolute);
                                                        //}
                                                        Image i = new Image()
                                                        {
                                                            Height = 24,
                                                            Width = 24,
                                                            VerticalAlignment = System.Windows.VerticalAlignment.Center,
                                                            Source = new BitmapImage(imgs)
                                                        };
                                                        TextBlock tbfname = new TextBlock()
                                                        {
                                                            Text = (Ullity.Trim(fullname1) != "") ? fullname1 : uname1,
                                                            FontSize = 8,
                                                            TextAlignment = TextAlignment.Center
                                                        };
                                                        lbst.Children.Add(i);
                                                        lbst.Children.Add(tbfname);
                                                        CGlobalVariable.lsbCurentChats.Items.Add(lbst);
                                                        CGlobalVariable.lsbCurentChats.SelectedItem = lbst;
                                                    
                                                    }
                                                    a.Add(new TextBlock()
                                                    {
                                                        Text = Ullity.DecodeString(str1),
                                                        FontSize = 14,
                                                        Padding = new Thickness(50, 2, 2, 2),
                                                        Width = CGlobalVariable.lsbChatWindows.Width,
                                                        TextAlignment = System.Windows.TextAlignment.Right,
                                                        HorizontalAlignment = System.Windows.HorizontalAlignment.Stretch,
                                                        //Background = new SolidColorBrush(Color.FromArgb(30, 240, 10, 150)),
                                                        TextWrapping = TextWrapping.Wrap
                                                    });
                                                    if (CGlobalVariable.lstChatData.ContainsKey(uname1))
                                                    {
                                                        CGlobalVariable.lstChatData[uname1].chatData = a;
                                                    }
                                                    else { 
                                                        CGlobalVariable.lstChatData.Add(uname1, new Msgs()
                                                        {
                                                            contactboxid = -1,
                                                            curentchatboxid = 0,
                                                            chatData = a
                                                        });
                                                    }
                                                    
                                                    showChat(uname1);
                                                }));

                                                Ullity.Log(uname1 + " -> " + str1); 
                                                break;
                
            }
            Ullity.Log(message);
        }

        static void b_Click(object sender, RoutedEventArgs e)
        {
            Client.Send("adduser:" + Ullity.EncodeString(((Button)sender).Tag.ToString()),CGlobalVariable.connectedsock);
        }
        public static void showChat(string username) {
            if (CGlobalVariable.lstChatData.ContainsKey(username))
            {
                Msgs s = CGlobalVariable.lstChatData[username];
                CGlobalVariable.lsbChatWindows.Items.Clear();
                foreach (Object i in s.chatData) { 
                  CGlobalVariable.lsbChatWindows.Items.Add(i);
                }
              
            }
        }
      

        public static void Send(String text, Socket sock)
        {
            try
            {
                SocketAsyncEventArgs ed = new SocketAsyncEventArgs();
                byte[] buffer = Encoding.UTF8.GetBytes(text + "\n");
                ed.SetBuffer(buffer, 0, buffer.Length);
                sock.SendAsync(ed);
            }
            catch { CGlobalVariable.IsDisconnected = true; }
        }
        

    }
}
